package com.fyb.doublecache.common;

import org.springframework.data.redis.core.script.DefaultRedisScript;

/**
 * @Author：MR.FANG
 * @name：constants
 * @Date：2025/7/3 上午10:24
 */
public class Constants {

    //锁前缀
    public static final String LOCK_PREFIX = "lock:algorithm:";
    //锁超时时间(秒)
    public static final int LOCK_TIMEOUT = 10;

    public static final DefaultRedisScript<Long> LOCK_SCRIPT = new DefaultRedisScript<>();
    public static final DefaultRedisScript<Long> UNLOCK_SCRIPT = new DefaultRedisScript<>();

    static {
        // 加锁脚本
        LOCK_SCRIPT.setScriptText(
                "if redis.call('setnx', KEYS[1], ARGV[1]) == 1 then " +
                        "redis.call('expire', KEYS[1], ARGV[2]) " +
                        "return 1 " +
                        "else " +
                        "return 0 " +
                        "end"
        );
        LOCK_SCRIPT.setResultType(Long.class);

        // 解锁脚本
        UNLOCK_SCRIPT.setScriptText(
                "if redis.call('get', KEYS[1]) == ARGV[1] then " +
                        "return redis.call('del', KEYS[1]) " +
                        "else " +
                        "return 0 " +
                        "end"
        );
        UNLOCK_SCRIPT.setResultType(Long.class);
    }
}
